package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2021/12/29 09:51
 */
@Service
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;
    
    @Autowired
    TransactionTemplate txTemplate;

    @Override
    public void transfer(Integer fromId, Integer destId, Integer money) {
        //原始money
        Integer fromMoney = accountMapper.selectMoneyById(fromId);
        Integer destMoney = accountMapper.selectMoneyById(destId);
        //计算转账后的money
        fromMoney -= money;
        destMoney += money;
        //execute →开启事务、 transactionCallBack里的doInTransaction、提交事务
        Integer finalFromMoney = fromMoney;
        Integer finalDestMoney = destMoney;
        Object execute = txTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                // 写的是包含事务的代码
                //执行更新，更新转账后的money
                accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;  //发生异常
                accountMapper.update(destId, finalDestMoney);

                return "doInTransaction";//5
            }
        });
        System.out.println(execute);
    }
}
